﻿using System;
using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
	public class AuthorizeAjaxAttribute : AuthorizeAttribute
	{
		private readonly string _loginUrl;

		public AuthorizeAjaxAttribute(string loginUrl)
		{
			Guard.NotNullOrEmpty(loginUrl, "loginUrl");

			_loginUrl = loginUrl;
		}

		public override void OnAuthorization(AuthorizationContext filterContext)
		{
			Guard.NotNull(filterContext, "filterContext");

			if (filterContext.HttpContext.Request.IsAjaxRequest()
			    && !AuthorizeCore(filterContext.HttpContext))
			{
				filterContext.Result = new UnauthorizedAjaxResult(_loginUrl);
			}
			else
			{
				base.OnAuthorization(filterContext);
			}
		}
	}
}